package com.example.foo.admin.task;

import java.util.List;

import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.ftt.FttLevel;
import com.example.foo.ftt.FttUserException;
import com.example.foo.ftt.model.FttUser;
import com.example.foo.ftt.query.FttUserQuery;
import com.example.foo.ftt.service.FttUserFacadeService;
import com.example.foo.ftt.service.FttUserService;

//网体升级任务
@org.springframework.stereotype.Component("fttUserFttLevelUpgradeTask")
public class FttUserFttLevelUpgradeTask {

	private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(getClass());

	private final FttUserService fttUserService;
	private final FttUserFacadeService fttUserFacadeService;

	public FttUserFttLevelUpgradeTask(FttUserService fttUserService,
			FttUserFacadeService fttUserFacadeService) {
		this.fttUserService = fttUserService;
		this.fttUserFacadeService = fttUserFacadeService;
	}

	public void execute() throws Exception {
		for (FttLevel fttLevel : FttLevel.values()) {
			if (fttLevel == FttLevel.F0 || fttLevel == FttLevel.F7) {
				continue;
			}

			FttUserQuery fttUserQuery = new FttUserQuery();
			fttUserQuery.setFttLevel(fttLevel);

			for (Pageable fttUserPageable = new Pageable(1, 100); ; fttUserPageable = fttUserPageable.next()) {
				PageResult<FttUser> fttUserPageResult = fttUserService.findFttUsers(fttUserQuery, fttUserPageable);
				List<FttUser> fttUsers = fttUserPageResult.getRows();
				if (fttUsers.isEmpty()) {
					break;
				}

				for (FttUser fttUser : fttUsers) {
					try {
						fttUserFacadeService.updateFttUserFttLevelUpgrade(fttUser.getId());
					} catch (Exception e) {
						throw new FttUserException(String.format("FttUser#%s", fttUser.getId()), e);
					}
				}
			}

		}

		log.info("DONE!");
	}

}
